package com.bidevalution.business.impl;

import com.bidevalution.business.service.BeReplyEnrollService;
import com.bidevalution.business.service.FaceCheckService;
import com.bidevalution.dao.entity.BeReplyEnroll;
import com.bidevalution.support.face.AesCrypt;
import com.bidevalution.support.face.RandomUtil;
import com.bidevalution.support.face.SHA1;
import com.qtp.core.common.HttpTookit;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;

@Service
public class FaceCheckServiceImpl implements FaceCheckService {

	private Logger logger = Logger.getLogger(getClass());
	private final static String faceCheckUrl = "http://122.228.31.41:8080/core/api/checkIdcardBaseFace";
	private final static String appId = "2661c39a7589e8d4ebf3e8c1cd15e71f";
	private final static String appKey = "244dec63bb23f74031e5ce8a863ab0f8";
	@Value("${upload.file.path}")
	private String uploadFilePath;
	@Autowired
	private BeReplyEnrollService beReplyEnrollService;
	private Logger log = Logger.getLogger(getClass());

	@Override
	public Response<String> check(MultipartFile file, String card, String name, String replyEnrollId) {

		try {
			Map<String, String> dataMap = new LinkedHashMap<String, String>();
			dataMap.put("idNumber", card);
			dataMap.put("name", name);
			dataMap.put("photo", getBase64(file.getInputStream()));
			String dataJson = GsonUtil.toJson(dataMap);
			String dataStr = new AesCrypt(appId, appKey).encrypt(dataJson);
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("encryptData", dataStr);
			String requestId = getRequestId();
			String nonce = RandomUtil.getRandomStr(16);
			String timestamp = Long.toString(new Date().getTime());
			String signature = SHA1.getSHA1(appId, appKey, timestamp, nonce, requestId, GsonUtil.toJson(paramMap));
			String result = sendData(faceCheckUrl + "?appId=" + appId + "&nonce=" + nonce + "&timestamp=" + timestamp
					+ "&requestId=" + requestId + "&signature=" + signature, GsonUtil.toJson(paramMap));
			logger.info(result);
			if (result != null) {
				Map<String, Object> resultMap = GsonUtil.jsonToMapWithGson(result);
				if ("0".equals(resultMap.get("code"))) {
					String fileId = "";
					try {
						fileId = HttpTookit.sendPostInputstream(
								uploadFilePath + "/fileUploadController/uploadWholeFile.do", file.getInputStream(),
								UUID.randomUUID().toString()+".jpeg", null);
					} catch (IOException e) {

					}
					if (StringUtils.isEmpty(fileId)) {
						return Response.fail("上传失败",10000);
					}
					BeReplyEnroll beReplyEnroll = beReplyEnrollService.selectById(replyEnrollId);
					beReplyEnroll.setFaceFileId(fileId);
					beReplyEnrollService.updateIdentity(beReplyEnroll);
					return Response.ok();
				} else {
					return Response.fail((String) resultMap.get("err"));
				}

			} else {
				return Response.fail("身份验证接口调用异常",10000);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return Response.fail(e.getMessage(),10000);
		}
	}

	public String getBase64(InputStream in) throws IOException {
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = in.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();
		} catch (IOException e) {
            log.error(e.getMessage(), e);
			throw e;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
                    log.error(e.getMessage(), e);
				}
			}
		}
		return new String(Base64.encodeBase64(data));
	}

	/**
	 * BASE转图片
	 * 
	 * @param baseStr   base64字符串
	 * @param imagePath 生成的图片
	 * @return
	 * @throws IOException
	 */
	public void base64ChangeImage(String baseStr, String imagePath) throws IOException {
		OutputStream out = null;
		try {
			// 解密
			byte[] b = Base64.decodeBase64(baseStr);
			// 处理数据
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			out = new FileOutputStream(imagePath);
			out.write(b);
			out.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			if (out != null) {

				out.close();
			}
		}
	}

	public static String getRequestId() {
		String base = "0123456789";
        Random random ;
        try {
            random = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            random = new Random();
        }
        StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return DateUtil.getCurrentDateStr("yyyyMMddHHmmss") + "01" + sb;
	}

	public static String sendData(String url, String data) throws Exception {
		// 声明httpPost请求
		HttpPost httpPost = new HttpPost(url);
		// 配置超时时间
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(1000).setRedirectsEnabled(true).build();
		// 设置超时时间
		httpPost.setConfig(requestConfig);
		httpPost.addHeader(new BasicHeader("Content­Type", "application/json"));
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 判断map不为空

		// 创建form表单对象
		StringEntity myEntity = new StringEntity(data, ContentType.APPLICATION_JSON);// 构造请求数据

		// 把表单对象设置到httpPost中
		httpPost.setEntity(myEntity);
		// 使用HttpClient发起请求，返回response
		CloseableHttpResponse response = httpClient.execute(httpPost);

		// 解析response封装返回对象httpResult
		if (response.getEntity() != null) {
			return EntityUtils.toString(response.getEntity(), "UTF-8");
		}
		return null;
	}

}
